package com.wit.witmg.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wit.witmg.entity.*;
import com.wit.witmg.mapper.TProdmaterMapper;
import com.wit.witmg.service.ITMatOutputService;
import com.wit.witmg.service.ITProdmaterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wit.witmg.service.ITProdstockService;
import com.wit.witmg.service.ITProdtaskService;
import com.wit.witmg.util.ErrorCode;
import com.wit.witmg.util.JsonResult;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bob
 * @since 2024-12-23
 */
@Service
@RequiredArgsConstructor
public class TProdmaterServiceImpl extends ServiceImpl<TProdmaterMapper, TProdmater> implements ITProdmaterService {

    final ITProdstockService stockService;
    final ITMatOutputService outputService;
    final ITProdtaskService taskService;
    @Override
    public Object add(HttpServletRequest request, String json) {
        TProdmater t= JSON.parseObject(json,TProdmater.class);
        if(t.getId()>0){
            boolean bl=  updateById(t);
            if(!bl){
                return JsonResult.error(ErrorCode.ERR_200);
            }
        }else{
            t.setDate(new Date());
            boolean bl= save(t);
            if(!bl){
                return JsonResult.error(ErrorCode.ERR_504);
            }
        }
        return JsonResult.success(t);
    }

    @Override
    public Object get(HttpServletRequest request, String size, String bn) {
        QueryWrapper<TProdmater> qw=new QueryWrapper<>();
        if(size!=null){
            qw.like("size",size);
            return JsonResult.success(list(qw));
        }
        if( bn!=null){
            qw.like("bn",bn);
            return JsonResult.success(list(qw));
        }
        return JsonResult.error(ErrorCode.ERR_200);
    }

    @Override
    public Object del(HttpServletRequest request, Integer id) {
        boolean bl= removeById(id);
        if(bl) {
            return JsonResult.success();
        }
        return JsonResult.error(ErrorCode.ERR_200);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object getqt(HttpServletRequest request,String bn,Double mqt,Integer pid, Long eid, String ena,Integer oid) {
        //bn精确匹配一条BOM表数据，根据mlist每条数据进行如下操作：先生成一条领料表数据，bn、na、size、remark、unit不变，oqt、amount、outdate为空，stat为0，id为自增，
        // pid用传入的参数，pqt等于mlist中的dose*参数mqt的值；根据其mlist中的bn查询库存表，将出库表的领料pqt的数字累加到库存表锁库数量pqt中，将库存表qt添加到mlist新增字段qt中返回，若不存在则qt为0。
        //同时还要把生产计划表t_prodtask的stat改为1 根据pid=id
        if (bn == null || bn.isEmpty()) {
            return JsonResult.error(ErrorCode.ERR_200);
        }
        QueryWrapper<TProdmater> qw = new QueryWrapper<>();
        qw.eq("bn", bn);
        qw.last("limit 1");
        TProdmater t = getOne(qw);

        if (t == null || t.getMlist() == null) {
            return JsonResult.error(ErrorCode.ERR_200);
        }

        JSONArray arr = JSON.parseArray(t.getMlist());
        if (arr == null || arr.isEmpty()) {
            return JsonResult.error(ErrorCode.ERR_200);
        }
        ArrayList<TMatOutput> outList = new ArrayList<>();

        // 收集所有需要查询的bn值
        Set<String> bns = new HashSet<>();
        for (int i = 0; i < arr.size(); i++) {
            JSONObject obj = arr.getJSONObject(i);
            if (obj != null && obj.containsKey("bn")) {
                String itemBn = obj.getString("bn");
                if (itemBn != null) {
                    bns.add(itemBn);
                }
                TMatOutput entity = new TMatOutput();
                entity.setOid(oid);
                entity.setBn(itemBn);
                entity.setNa(obj.getString("na"));
                if(obj.containsKey("size")) entity.setSize(obj.getString("size"));
                if(obj.containsKey("unit")) entity.setUnit(obj.getString("unit"));
                entity.setPid(pid);
                entity.setEid(eid);
                entity.setEna(ena);
                entity.setPbn(bn);
                if(obj.containsKey("dose")) {
                    double d=obj.getDouble("dose") * mqt;
                    entity.setPqt(d);
                    obj.put("pqt",d);
                }
                outList.add(entity);
            }
        }
        List<TProdstock> stockList=new ArrayList<>();

        // 批量查询库存信息
        Map<String, TProdstock> stockMap = stockService.list(new QueryWrapper<TProdstock>().in("bn", bns))
                .stream()
                .collect(Collectors.toMap(TProdstock::getBn, stock -> stock));

        // 更新JSONArray中的qt字段
        for (int i = 0; i < arr.size(); i++) {
            JSONObject obj = arr.getJSONObject(i);
            if (obj != null && obj.containsKey("bn")) {
                String itemBn = obj.getString("bn");
                if (itemBn != null && stockMap.containsKey(itemBn)) {
                    TProdstock t2 = stockMap.get(itemBn);
                    obj.put("qt", t2 != null ? t2.getQt() : 0);
                    if (t2 != null) {
                        t2.setPqt(t2.getPqt() + obj.getDouble("pqt"));
                        obj.put("pqt",t2.getPqt());
                        stockList.add(t2);
//                        stockService.updateById(t2);
                    }
                }else{
                    obj.put("qt", 0);
                }
            }
        }
        if(outputService.saveBatch(outList)) {
            if(!stockList.isEmpty()){
                if ( !stockService.updateBatchById(stockList)) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//回滚
                    return JsonResult.error(ErrorCode.ERR_504);
                }
            }
            if(!taskService.updateById(new TProdtask().setId(pid).setStat(1))) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//回滚
                return JsonResult.error(ErrorCode.ERR_504);
            }
        }
       
        return JsonResult.success(arr);
    }
}
